package com.pointcircle.core.web.auth;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.pointcircle.core.ApplicationContextHolder;
import com.pointcircle.core.entity.Role;
import com.pointcircle.core.entity.User;
import com.pointcircle.core.repository.RolePermissionRepository;
import com.pointcircle.core.repository.UserRoleRepository;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AuthInfo {
	public AuthInfo(String jwtToken, User user) {
		this.jwtToken = jwtToken;
		this.user = user;
	}
	@JsonIgnore
	private User user;
	private String jwtToken;
	
	@JsonProperty("userId")
	public String userId() {
		return user.getId();
	}
	@JsonProperty("username")
	public String username() {
		return user.getUsername();
	}
	@JsonProperty("realname")
	public String realname() {
		return user.getRealname();
	}
	@JsonProperty("permissionIds")
	public List<String> permissionIds() {
		UserRoleRepository userRoleRepository = ApplicationContextHolder.getBean(UserRoleRepository.class);
		List<Role> roles = userRoleRepository.findByUser(user).stream()
			.map(userRole -> userRole.getRole())
			.collect(Collectors.toList());
		RolePermissionRepository rolePermissionRepository = ApplicationContextHolder.getBean(RolePermissionRepository.class);
		Set<String> permissionSet = new TreeSet<String>();
		roles.forEach(role -> {
			rolePermissionRepository.findByRole(role).forEach(rolePermission -> {
				permissionSet.add(rolePermission.getPermission());
			});
		});
		return new LinkedList<String>(permissionSet);
	}
}
